<?php
namespace app\admin\controller\v1;

use app\lib\exception\ForbiddenException;
use think\Controller;
use think\Request;

class BaseController extends Controller
{
    protected $admin;
    public function __construct()
    {
        parent::__construct();
//        $this->checkPermission();
    }

    //验证管理员身份
    public function checkPermission(){
        $request = Request::instance();
        $action = strtolower($request->method());
        $identity = strtolower(explode('.',$request->controller())[1]);

        //到请求的header里面获取token
        $token = $request->header('token');

        //有些链接是不需要token就能访问的
        $no_permission_list = config('secure.no_permission_list');
        if(in_array($identity,$no_permission_list)) return ;

        if(empty($token) || empty($admin = cache($token))) throw (new ForbiddenException());

        //是不是超级管理员，是就放行
        if($admin['is_supper']) return ;

        //检验是否有权限
        $flag = false;
        foreach ($admin['permission'] as $v){
            if($action == $v['action'] && $identity == $v['source_identity']) $flag = true;
        }
        if(!$flag) throw new ForbiddenException();
        $this->admin = $admin;
    }

//    public function SourcePolicy(){
//        //检测访问的资源是否存在
//        $source = Db::table(config('database.prefix').'source')->where(['identity'=>$this->request['identity']])->find();
//        if(!$source) throw new BaseException(['msg'=>'资源未找到','errorCode'=>'10001']);
//        $this->source = $source;
//    }
}
